package ru.mcfr.oxygen.framework.operations;

import ro.sync.ecss.extensions.api.ArgumentDescriptor;
import ro.sync.ecss.extensions.api.AuthorOperationException;
import ro.sync.ecss.extensions.api.node.AuthorDocumentFragment;

import javax.swing.text.BadLocationException;

public class InsertElementOperation extends McfrBaseAuthorOperation {

    private String mode;
    private int ELEMENT_NAME = 0;
    private int ATTRIBUTES = 1;
    private int ATTRIBUTES_VALUES = 2;
    private int OPERATION_MODE = 3;

    {
        description = "Вставка элемента";

        argumentsNameArray = new String[]{
                "элемент",
                "атрибуты",
                "значения атрибутов",
                "режим"
        };

        argumentsTypesArray = new Object[]{
                ArgumentDescriptor.TYPE_STRING,
                ArgumentDescriptor.TYPE_STRING,
                ArgumentDescriptor.TYPE_STRING,
                ArgumentDescriptor.TYPE_STRING
        };

        argumentsDescriptionsArray = new String[]{
                "вставляемый элемент",
                "список атрибутов через запятую",
                "значения атрибутов через запятую",
                "режим выполнения"
        };

    }

    private String makeElementString(String fragment){
        String result = "";
        String attrString = "";
        try {
            attrString = makeAttrBlock(argumentsValues.get(argumentsNameArray[ATTRIBUTES]),
                    argumentsValues.get(argumentsNameArray[ATTRIBUTES_VALUES]));
        } catch (Exception e) {
        }

        result = "<" + argumentsValues.get(argumentsNameArray[ELEMENT_NAME]);
        if (!attrString.isEmpty())
            result += " " + attrString;
        result += ">";
        result += fragment;
        result += "</" + argumentsValues.get(argumentsNameArray[ELEMENT_NAME]) + ">";
        return result;
    }

    @Override
    public void doMainOperation() {

    }

    @Override
    public void doOperationWithSelected() throws AuthorOperationException, BadLocationException {
        mode = argumentsValues.get(argumentsNameArray[OPERATION_MODE]);
        if (mode.equalsIgnoreCase("texted")) {
            String selectedText = authorAccess.getEditorAccess().getSelectedText();
            if (!selectedText.isEmpty()) {
                String textFragment = makeElementString(selectedText);
                controller.delete(authorAccess.getEditorAccess().getSelectionStart(), authorAccess.getEditorAccess().getSelectionEnd() - 1);
                controller.insertXMLFragmentSchemaAware(textFragment, authorAccess.getEditorAccess().getSelectionStart());
                authorAccess.getEditorAccess().setCaretPosition(caretPosition);
            } else {
                String textFragment = makeElementString("");
                controller.delete(authorAccess.getEditorAccess().getSelectionStart(), authorAccess.getEditorAccess().getSelectionEnd() - 1);
                controller.insertXMLFragmentSchemaAware(textFragment, authorAccess.getEditorAccess().getSelectionStart());
                authorAccess.getEditorAccess().setCaretPosition(caretPosition);
            }
        } else if (mode.equalsIgnoreCase("block")) {
            int start = controller.getNodeAtOffset(startCaretPosition).getStartOffset();
            int end = controller.getNodeAtOffset(endCaretPosition).getEndOffset();
            String textBlock = "";
            if (end > start) {
                AuthorDocumentFragment my_fragment = controller.createDocumentFragment(start, end);
                textBlock = controller.serializeFragmentToXML(my_fragment);
                textBlock = textBlock.replace(" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"", "");
                controller.delete(start, end);
            } else {
                start = caretPosition;
            }
            String textFragment = makeElementString(textBlock);
            controller.insertXMLFragmentSchemaAware(textFragment, start);
            authorAccess.getEditorAccess().setCaretPosition(caretPosition);
        } else if (mode.contains("remove")){
            if (selectedElement.getName().equals(argumentsValues.get(argumentsNameArray[ELEMENT_NAME]))){
                String text = selectedElement.getTextContent();
                controller.deleteNode(selectedElement);
                controller.insertText(startCaretPosition, text);
            }
        }
    }

    @Override
    public void doOperationAtCaretPos() throws AuthorOperationException {
        String textFragment = makeElementString("");
        controller.insertXMLFragmentSchemaAware(textFragment, caretPosition);
        authorAccess.getEditorAccess().setCaretPosition(caretPosition);
    }
}
